package com.zhai.test.algorithm.array;

/**
 * @Description: 二分查找
 * @ClassName: MiddleQuery
 * @Author: zhaiyongxin
 * @Date: 2025/3/11 17:50
 * @Version: 1.0
 */
public class MiddleQuery {
    public static void main(String[] args) {
        int[] array  = new int[]{5};
        int target = 5;
        int targetIdx = getTargetIdx2(array, target);
        System.out.println(targetIdx);
    }

    public static int getTargetIdx1(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (target == array[middle]) {
                return middle;
            } else if (target < array[middle]) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
        return -1;
    }

    public static int getTargetIdx2(int[] array, int target) {
        int left = 0;
        int right = array.length;
        while (left < right) {
            int middle = left + (right - left) / 2;
            if (target == array[middle]) {
                return middle;
            } else if (target < array[middle]) {
                right = middle;
            } else {
                left = middle + 1;
            }
        }
        return -1;
    }
}
